package main

import (
	"fmt"
	"go_rpc/grpc_stream/proto"
	"google.golang.org/grpc"
	"net"
	"sync"
	"time"
)

const PORT = ":50052"

type server struct {
	proto.UnimplementedGreeterServer
}

func (s *server) GetStream(data *proto.StreamReqData, streamServer proto.Greeter_GetStreamServer) error {
	i := 0
	for {
		i++
		_ = streamServer.Send(&proto.StreamResData{Data: fmt.Sprintf("%v", time.Now().Unix())})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}

func (s *server) PostStream(streamServer proto.Greeter_PostStreamServer) error {
	for {
		a, err := streamServer.Recv()
		if err != nil {
			fmt.Println("异常:", err.Error())
			break
		}
		fmt.Println(a.Data)
	}
	return nil
}

func (s *server) AllStream(streamServer proto.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := streamServer.Recv()
			fmt.Printf("收到客户端消息: %v", data)

		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = streamServer.Send(&proto.StreamResData{Data: "我是服务器"})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	return nil
}

func (s *server) mustEmbedUnimplementedGreeterServer() {

}

func main() {
	lis, err := net.Listen("tcp", PORT)
	// 服务端模式
	if err != nil {
		fmt.Println("异常:", err.Error())
		panic(err)
	}
	s := grpc.NewServer()
	proto.RegisterGreeterServer(s, &server{})
	err = s.Serve(lis)
	if err != nil {
		fmt.Println("异常:", err.Error())
		panic(err)
	}

}
